const { pool } = require('../config/db');

exports.getAllGroups = async (req, res) => {
    const [rows] = await pool.query('SELECT * FROM redirect_groups ORDER BY sort_order');
    return res.json(rows);
};

exports.getEnabledGroups = async (req, res) => {
    const [rows] = await pool.query('SELECT * FROM redirect_groups WHERE is_enabled = TRUE ORDER BY sort_order');
    return res.json(rows);
};

exports.getGroupById = async (req, res) => {
    const { id } = req.params;
    const [[group]] = await pool.query('SELECT * FROM redirect_groups WHERE id = ?', [id]);
    if (!group) {
        return res.status(404).send('Group not found');
    }
    return res.json(group);
};

exports.searchGroups = async (req, res) => {
    const { group_name, sort_order, is_enabled } = req.query;
    let query = 'SELECT * FROM redirect_groups WHERE 1=1';
    const params = [];

    if (group_name) {
        query += ' AND group_name LIKE ?';
        params.push(`%${group_name}%`);
    }

    if (sort_order) {
        query += ' AND sort_order = ?';
        params.push(sort_order);
    }

    if (is_enabled !== undefined) {
        query += ' AND is_enabled = ?';
        params.push(is_enabled === 'true' || is_enabled === true);
    }

    query += ' ORDER BY sort_order';

    const [rows] = await pool.query(query, params);
    return res.json(rows);
};

exports.createGroup = async (req, res) => {
    try {
        // sort_order 默认值为 0, is_enabled 默认值为 true
        const { group_name, sort_order = 0, is_enabled = true } = req.body;

        if (!group_name) {
            return res.status(400).send('Group name is required');
        }

        const [result] = await pool.query(
            'INSERT INTO redirect_groups (group_name, sort_order, is_enabled) VALUES (?, ?, ?)',
            [group_name, sort_order, is_enabled]
        );

        return res.status(201).json({
            message: 'Group created successfully',
            id: result.insertId,
            group_name,
            sort_order,
            is_enabled
        });
    } catch (error) {
        console.error('Error creating group:', error);
        return res.status(500).send('Failed to create group');
    }
};

exports.updateGroup = async (req, res) => {
    try {
        const { id } = req.params;
        const updates = req.body;
        
        // 验证是否有要更新的字段
        if (Object.keys(updates).length === 0) {
            return res.status(400).send('No fields to update');
        }
        
        // 检查组是否存在
        const [[existingGroup]] = await pool.query('SELECT * FROM redirect_groups WHERE id = ?', [id]);
        if (!existingGroup) {
            return res.status(404).send('Group not found');
        }
        
        // 构建动态更新查询
        const fields = [];
        const values = [];
        
        if (updates.group_name !== undefined) {
            fields.push('group_name = ?');
            values.push(updates.group_name);
        }
        
        if (updates.sort_order !== undefined) {
            fields.push('sort_order = ?');
            values.push(updates.sort_order);
        }

        if (updates.is_enabled !== undefined) {
            fields.push('is_enabled = ?');
            values.push(updates.is_enabled);
        }
        
        if (fields.length === 0) {
            return res.status(400).send('No valid fields to update');
        }
        
        // 添加ID到参数数组
        values.push(id);
        
        // 执行更新
        await pool.query(
            `UPDATE redirect_groups SET ${fields.join(', ')} WHERE id = ?`, 
            values
        );
        
        // 获取更新后的数据
        const [[updatedGroup]] = await pool.query('SELECT * FROM redirect_groups WHERE id = ?', [id]);
        
        return res.json({
            message: 'Group updated successfully',
            group: updatedGroup
        });
    } catch (error) {
        console.error('Error updating group:', error);
        return res.status(500).send('Failed to update group');
    }
};

exports.deleteGroup = async (req, res) => {
    try {
        const { id } = req.params;
        
        // 检查组是否存在
        const [[existingGroup]] = await pool.query('SELECT * FROM redirect_groups WHERE id = ?', [id]);
        if (!existingGroup) {
            return res.status(404).send('Group not found');
        }
        
        // 检查是否有依赖关系（例如，是否有targets引用此group_id）
        const [relatedTargets] = await pool.query('SELECT COUNT(*) as count FROM redirect_targets WHERE group_id = ?', [id]);
        if (relatedTargets[0].count > 0) {
            return res.status(400).send('Cannot delete group: it is being used by one or more targets');
        }
        
        // 执行删除
        await pool.query('DELETE FROM redirect_groups WHERE id = ?', [id]);
        
        return res.json({
            message: 'Group deleted successfully',
            id: parseInt(id)
        });
    } catch (error) {
        console.error('Error deleting group:', error);
        return res.status(500).send('Failed to delete group');
    }
};

// 启用分组
exports.enableGroup = async (req, res) => {
    try {
        const { id } = req.params;

        // 检查组是否存在
        const [[existingGroup]] = await pool.query('SELECT * FROM redirect_groups WHERE id = ?', [id]);
        if (!existingGroup) {
            return res.status(404).send('Group not found');
        }

        // 启用分组
        await pool.query('UPDATE redirect_groups SET is_enabled = TRUE WHERE id = ?', [id]);

        // 获取更新后的数据
        const [[updatedGroup]] = await pool.query('SELECT * FROM redirect_groups WHERE id = ?', [id]);

        return res.json({
            message: 'Group enabled successfully',
            group: updatedGroup
        });
    } catch (error) {
        console.error('Error enabling group:', error);
        return res.status(500).send('Failed to enable group');
    }
};

// 禁用分组
exports.disableGroup = async (req, res) => {
    try {
        const { id } = req.params;

        // 检查组是否存在
        const [[existingGroup]] = await pool.query('SELECT * FROM redirect_groups WHERE id = ?', [id]);
        if (!existingGroup) {
            return res.status(404).send('Group not found');
        }

        // 检查是否还有其他启用的分组
        const [enabledGroups] = await pool.query('SELECT COUNT(*) as count FROM redirect_groups WHERE is_enabled = TRUE AND id != ?', [id]);
        if (enabledGroups[0].count === 0) {
            return res.status(400).send('Cannot disable the last enabled group. At least one group must remain enabled.');
        }

        // 禁用分组
        await pool.query('UPDATE redirect_groups SET is_enabled = FALSE WHERE id = ?', [id]);

        // 获取更新后的数据
        const [[updatedGroup]] = await pool.query('SELECT * FROM redirect_groups WHERE id = ?', [id]);

        return res.json({
            message: 'Group disabled successfully',
            group: updatedGroup
        });
    } catch (error) {
        console.error('Error disabling group:', error);
        return res.status(500).send('Failed to disable group');
    }
};

// 切换分组启用状态
exports.toggleGroupStatus = async (req, res) => {
    try {
        const { id } = req.params;

        // 检查组是否存在
        const [[existingGroup]] = await pool.query('SELECT * FROM redirect_groups WHERE id = ?', [id]);
        if (!existingGroup) {
            return res.status(404).send('Group not found');
        }

        // 如果当前是启用状态，要禁用时需要检查是否还有其他启用的分组
        if (existingGroup.is_enabled) {
            const [enabledGroups] = await pool.query('SELECT COUNT(*) as count FROM redirect_groups WHERE is_enabled = TRUE AND id != ?', [id]);
            if (enabledGroups[0].count === 0) {
                return res.status(400).send('Cannot disable the last enabled group. At least one group must remain enabled.');
            }
        }

        // 切换状态
        const newStatus = !existingGroup.is_enabled;
        await pool.query('UPDATE redirect_groups SET is_enabled = ? WHERE id = ?', [newStatus, id]);

        // 获取更新后的数据
        const [[updatedGroup]] = await pool.query('SELECT * FROM redirect_groups WHERE id = ?', [id]);

        return res.json({
            message: `Group ${newStatus ? 'enabled' : 'disabled'} successfully`,
            group: updatedGroup
        });
    } catch (error) {
        console.error('Error toggling group status:', error);
        return res.status(500).send('Failed to toggle group status');
    }
};